package com.motong.gongdan.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.CommonTree;
import com.motong.gongdan.mapper.CommonTreeMapper;
import com.motong.gongdan.vo.system.tree.query.TreeQuery;
import com.motong.gongdan.vo.system.tree.vo.TreeVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommonTreeService extends ServiceImpl<CommonTreeMapper, CommonTree> {


    /**
     * 获取指定模块的树结构
     */
    public List<TreeVo> getList(TreeQuery param) {
        List<TreeVo> data = this.baseMapper.getList(param);
        // 递归出组织树
        if (!CollectionUtil.isEmpty(data)) {
            Map<String, List<TreeVo>> parentIdDataMap = data.stream().collect(Collectors.groupingBy(TreeVo::getParentId));
            this.recursion("0", parentIdDataMap, param.getLabel());
            List<TreeVo> tempData = new ArrayList<>();
            parentIdDataMap.forEach((key, value) -> {
                tempData.addAll(value);
            });
            data = tempData;
            if (!param.isTreeStructure()) {
                List<TreeVo> treeVos = new ArrayList<>();
                this.toList(data, treeVos);
                data = treeVos;
            }
        }
        return data;

    }


    /**
     * @param parentNodeId    节点id
     * @param parentIdDataMap 父节点id数据映射
     * @param likeName        查询相似
     */
    public void recursion(String parentNodeId, Map<String, List<TreeVo>> parentIdDataMap, String likeName) {
        List<TreeVo> startNodes = parentIdDataMap.get(parentNodeId);
        if (!CollectionUtils.isEmpty(startNodes)) {
            Iterator<TreeVo> nodesIterator = startNodes.iterator();
            while (nodesIterator.hasNext()) {
                TreeVo item = nodesIterator.next();
                boolean isSuit = (Objects.isNull(likeName) || item.getLabel().contains(likeName));
                this.recursion(item.getValue(), parentIdDataMap, isSuit ? null : likeName);
                if (isSuit) {
                    item.setChild(parentIdDataMap.get(item.getValue()));
                    parentIdDataMap.remove(item.getValue());
                } else {
                    nodesIterator.remove();
                }
            }
        }
    }


    /**
     * @param treeList  树节点数组
     * @param finalList 查询相似
     */
    public void toList(List<TreeVo> treeList, List<TreeVo> finalList) {
        treeList.forEach(i -> {
            TreeVo newTreeVo = BeanUtil.toBean(i, TreeVo.class);
            finalList.add(newTreeVo.setChild(Collections.emptyList()));
            if (!CollectionUtils.isEmpty(i.getChild())) {
                this.toList(i.getChild(), finalList);
            }
        });
    }
}
